package com.example.s.Activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.s.R;
import com.example.s.adapter.InnerHolder;
import com.example.s.adapter.MyRecyclerViewAdapter;
import com.example.s.bean.RecContent;
import com.example.s.bean.WorksComment;
import com.example.s.listener.OnDoubleClickListener;
import com.example.s.utils.LiveDataBus;
import com.example.s.utils.MyUtils;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class WorksDetailActivity extends BaseActivity {
    private NestedScrollView sv;

    private ImageView back;
    private TextView title;
    private CircleImageView headPhoto;
    private TextView name;
    private TextView fans;
    private TextView works;
    private TextView likesAndCollctions;
    private TextView follow;
    private TextView content;
    private ImageView moreContent;
    private RecyclerView contentPicRv;
    private LinearLayout showAllPic;
    private VideoView vv;
    private ImageView playOrPause;
    private AppCompatSeekBar sb;

    private WebView wv;
    private ImageView morePicIv;


    private RecyclerView rv;
    private TextView comment;
    private FrameLayout likesBg;
    private TextView likes;
    private FrameLayout collectionBg;
    private TextView collections;
    private FrameLayout share;
    private boolean canPlay = false;
    private FrameLayout videoContainer;
    private Handler mHandler;
    private ImageView videoCover;
    private List<WorksComment> mWorksCommentList = new ArrayList<>();
    private MyRecyclerViewAdapter<WorksComment> mWorksCommentAdapter;
    private Uri VIDEO_URL = Uri.parse("android.resource://com.example.s/raw/" + R.raw.fakexq);
    private boolean isMoreContentTextExpan = false;
    private boolean isMoreContentPicExpan = false;
    private LinearLayout sendCommentContainer;
    private EditText etComment;
    private TextView send;
    private LinearLayout allContainer;
    private RelativeLayout userContainer;
    private int height;  //默认内容高度
    private int picContainerSubHeight; //默认内容图片容器高度
    private int picContainerAllHeight; //全部内容图片容器高度
    private LinearLayout functionBar;
    private TextView worksVideoTitle;
    private Dialog picDialog;
    private Animation animation; //底部functionBar 显示动画
    private Animation animation2; //底部functionBar 消失动画
    List<Integer> picList = new ArrayList<>();

    private int maxHeight;
    private TextView contentShadow;


    private MyRecyclerViewAdapter<Integer> contentPicAdapter;

    private void initView() {

        sv = (NestedScrollView) findViewById(R.id.sv);
        worksVideoTitle = (TextView) findViewById(R.id.worksVideoTitle);
        morePicIv = (ImageView) findViewById(R.id.morePicIv);
        back = (ImageView) findViewById(R.id.back);
        title = (TextView) findViewById(R.id.title);
        headPhoto = (CircleImageView) findViewById(R.id.headPhoto);
        name = (TextView) findViewById(R.id.name);
        fans = (TextView) findViewById(R.id.fans);
        works = (TextView) findViewById(R.id.works);
        likesAndCollctions = (TextView) findViewById(R.id.likesAndCollctions);
        follow = (TextView) findViewById(R.id.follow);
        content = (TextView) findViewById(R.id.content);
        moreContent = (ImageView) findViewById(R.id.moreContent);
        contentPicRv = (RecyclerView) findViewById(R.id.contentPicRv);
        showAllPic = (LinearLayout) findViewById(R.id.showAllPic);
        vv = (VideoView) findViewById(R.id.vv);
        playOrPause = (ImageView) findViewById(R.id.playOrPause);
        sb = (AppCompatSeekBar) findViewById(R.id.sb);
        rv = (RecyclerView) findViewById(R.id.rv);
        comment = (TextView) findViewById(R.id.comment);
        likesBg = (FrameLayout) findViewById(R.id.likesBg);
        likes = (TextView) findViewById(R.id.likes);
        collectionBg = (FrameLayout) findViewById(R.id.collectionBg);
        collections = (TextView) findViewById(R.id.collections);
        share = (FrameLayout) findViewById(R.id.share);
        videoContainer = (FrameLayout) findViewById(R.id.videoContainer);
        videoCover = (ImageView) findViewById(R.id.videoCover);
        functionBar = (LinearLayout) findViewById(R.id.functionBar);
        wv = (WebView) findViewById(R.id.wv);
        userContainer = (RelativeLayout) findViewById(R.id.userContainer);
        allContainer = (LinearLayout) findViewById(R.id.allContainer);
        sendCommentContainer = (LinearLayout) findViewById(R.id.sendCommentContainer);
        etComment = (EditText) findViewById(R.id.etComment);
        send = (TextView) findViewById(R.id.send);
        contentShadow = (TextView) findViewById(R.id.contentShadow);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_works_detail);

        initView();

        //初始 content

        content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                height = content.getHeight();
                Log.d(TAG, "onCreate: 第一次" + height);
                content.setMaxHeight(maxHeight = MyUtils.getInstance().dip2px(WorksDetailActivity.this, 150));
                Log.d(TAG, "onCreate:maxH 第一次" + maxHeight);
                content.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }

        });


        name.setFocusable(true);
        name.setFocusableInTouchMode(true);
        name.requestFocus();


        picList.add(R.drawable.yyw_xq1);
        picList.add(R.drawable.yyw_xq2);
        picList.add(R.drawable.yyw_xq4);
        picList.add(R.drawable.yyw_xq3);
        picList.add(R.drawable.yyw_xq5);


        allContainer.setOnClickListener(new OnDoubleClickListener() {
            @Override
            public void onDoubleClick(View v) {
                //全局点赞？？？
                Log.d(TAG, "onDoubleClick: 双击");
            }
        });

        /**
         * funcitonBar animation
         */
        animation = AnimationUtils.loadAnimation(this, R.anim.bottom_to_top);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                functionBar.setVisibility(View.VISIBLE);
                Log.d(TAG, "onAnimationStart: ");
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        animation2 = AnimationUtils.loadAnimation(this, R.anim.top_to_bottom);
        animation2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                functionBar.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        /**
         * 标题栏吸顶  和 吸底
         */

        DisplayMetrics displayMetrics = new DisplayMetrics();
        WorksDetailActivity.this.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            final boolean[] flag = {false, false};
            final float[] y = {0, 0, 0, 0, 0, 0}; //用户信息栏的y，底部功能控制的y
            sv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @SuppressLint("ResourceAsColor")
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    /**
                     * 控制用户信息吸顶
                     */
                    if (!flag[0]) {
                        y[0] = userContainer.getY();
                        flag[0] = true;
                    }
                    if (oldScrollY > y[0]) {
                        //开始吸顶
                        LiveDataBus.getInstance().with("style", Integer.class).setValue(0);
                        userContainer.setBackgroundColor(Color.parseColor("#000038"));
                        userContainer.setY(scrollY);
                    } else {
                        LiveDataBus.getInstance().with("style", Integer.class).setValue(4);
                        userContainer.setBackgroundColor(android.R.color.transparent);
                        userContainer.setY(y[0]);

                    }

                    /**
                     * 控制底部标签
                     * 如果滚动到 “作品视频” 就显示到底部
                     */
                    if (!flag[1]) {
                        y[2] = functionBar.getY();
                        y[1] = worksVideoTitle.getY() + worksVideoTitle.getHeight() + userContainer.getHeight();
                        flag[1] = true;
                    }
                    if (oldScrollY > y[1] && functionBar.getVisibility() == View.INVISIBLE && (animation2.hasEnded() || !animation2.hasStarted())) {
                        functionBar.startAnimation(animation);
                    } else if (oldScrollY <= y[1] && functionBar.getVisibility() == View.VISIBLE && (animation.hasEnded() || !animation.hasStarted())) {
                        functionBar.startAnimation(animation2);
                    }

                }
            });
        }


        follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = follow.getText().toString();
                if (!s.contains("已")) {
                    follow.setText("已关注");

                } else {
                    View view2 = LayoutInflater.from(WorksDetailActivity.this).inflate(R.layout.base_dialog, null);
                    AlertDialog dialog = new AlertDialog.Builder(WorksDetailActivity.this).setView(view2).show();
                    WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                    attributes.width = MyUtils.getInstance().dip2px(WorksDetailActivity.this, 280);
                    dialog.getWindow().setAttributes(attributes);
                    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                    TextView tv = view2.findViewById(R.id.title);
                    tv.setText("确认要取消关注吗?");
                    view2.findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            follow.setText("关注");
                            dialog.dismiss();
                        }
                    });
                    view2.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                }
            }
        });
        LiveDataBus.getInstance().with("currentWorkDetail", RecContent.class).observe(this, new Observer<RecContent>() {
            @Override
            public void onChanged(RecContent recContent) {
                title.setText(recContent.getTitle());
                headPhoto.setImageResource(recContent.getHeadPhoto());
                name.setText("小老板");
                fans.setText(101 + fans.getText().toString());
                works.setText(3 + works.getText().toString());
                likesAndCollctions.setText(62 + likesAndCollctions.getText().toString());
            }
        });
        mHandler = new Handler(Looper.getMainLooper());
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        content.setText("一张表达人物故事照片当中，光线的氛围和色调，以及影调是渲染照片故事性的关键性要素。一般情况下，根据照片中人物关系、表情、动作等故事（主体/核心）内容的情感表达，配合适当的环境光线的氛围表达、色调，以及光影的，突出照片所传达出来的故事性。如此，可以让观者更深刻的感受到照片的故事性和情感性。\n" +
                "　　这里举个单例来进一步说明一下。照片中两个人物相对，一位蹲姿，一位站姿且手持雨伞。仿佛在述说这一段感情困惑或者其他让人略显忧郁的事情。\n" +
                "　　从照片原图来看，整个照片所要表达故事情节和情感意图已经很明显了。只是在自然光线下的故事氛围略有欠缺。比如整体环境光线略显平均，色调方面针对于故事性传达方面略显平庸。好了，照片的故事性渲染的调整方向和目标就有了。");


        loadMoreContent();

        setContentPic();

        setVideo();

        setWokrsCommentData();
        setWokrsComment();

        MyUtils.getInstance().showEtContainerBySoftkey(findViewById(android.R.id.content), sendCommentContainer);
        comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    sv.stopNestedScroll();
                }
                MyUtils.getInstance().showEtContainerBySoftkey(findViewById(android.R.id.content), sendCommentContainer);
                etComment.requestFocus();  //获得焦点
                InputMethodManager imm = (InputMethodManager) etComment.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//弹出小键盘
            }
        });


        allContainer.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                Log.d(TAG, "onScrollChanged: ");
                if (sendCommentContainer.getVisibility() == View.VISIBLE) {
                    InputMethodManager imm = (InputMethodManager) etComment.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(sendCommentContainer.getWindowToken(), 0);
                }
            }
        });

        showAllPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isMoreContentPicExpan) {
                    animationIvOpen(morePicIv);
                    picList.add(R.drawable.yywtx1);
                    picList.add(R.drawable.yywtx2);
                    isMoreContentPicExpan = true;
                } else {
                    animationIvClose(morePicIv);
                    picList.remove((Integer) R.drawable.yywtx1);
                    picList.remove((Integer) R.drawable.yywtx2);
                    isMoreContentPicExpan = false;
                }
                contentPicAdapter.notifyDataSetChanged();
            }
        });
    }

    private void setContentPic() {
        contentPicRv.setItemAnimator(new DefaultItemAnimator());
//        contentPicRv.setLayoutAnimation(new LayoutAnimationController(AnimationUtils.loadAnimation(this,R.anim.rv_fall_down_item)));
        contentPicRv.setLayoutManager(new LinearLayoutManager(WorksDetailActivity.this));
        contentPicRv.setAdapter(contentPicAdapter = new MyRecyclerViewAdapter<Integer>(picList, R.layout.rv_contentpic_item) {
            @Override
            public void handleData(InnerHolder holder, Integer item) {
                holder.setSrcResource(R.id.iv, item)
                        .setOnClickListener(R.id.iv, new View.OnClickListener() {
                            @Override
                            public void onClick(View view33) {

                                View view = LayoutInflater.from(WorksDetailActivity.this).inflate(R.layout.webview_dialog, null);
                                WebView wv2 = view.findViewById(R.id.wv);
                                picDialog = new Dialog(WorksDetailActivity.this);
                                picDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
                                picDialog.setContentView(view);
                                picDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0x00000000)); //设置背景透明
                                picDialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); //设置全屏显示
                                picDialog.getWindow().setGravity(Gravity.CENTER);
                                wv2.getSettings().setDisplayZoomControls(false);
                                wv2.getSettings().setBuiltInZoomControls(true);
                                //扩大比例的缩放
                                wv2.getSettings().setUseWideViewPort(true);
                                //自适应屏幕
                                wv2.getSettings().setLoadWithOverviewMode(true);
                                wv2.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //设置后可以拖动 不影响缩放


                                String resourceName = getResources().getResourceEntryName(item);//改用picPath
                                Log.d("", "onClick: " + resourceName);
                                wv2.loadUrl("file:///android_res/drawable/" + resourceName + ".png");  //url
                                picDialog.show();
                            }
                        });
            }
        }); //改String
    }

    /**
     * 创建下拉属性动画
     *
     * @param v
     * @param start
     * @param end
     * @return
     */
    private ValueAnimator createDropAnimator(final View v, int start, int end) {
        ValueAnimator animator = ValueAnimator.ofInt(start, end);
        animator.setDuration(500);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator arg0) {
                int value = (int) arg0.getAnimatedValue();
                ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
                layoutParams.height = value;
                v.setLayoutParams(layoutParams);

            }
        });
        return animator;
    }


    /**
     * 开启textView下拉动画
     */
    private void animateOpen() {
        maxHeight = content.getMaxHeight();
        ValueAnimator animator = createDropAnimator(content, maxHeight,
                height);

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                ViewGroup.LayoutParams layoutParams = content.getLayoutParams();
                layoutParams.height = height;
                content.setLayoutParams(layoutParams);
//                content.setMaxLines(Integer.MAX_VALUE);
//                content.setEllipsize(TextUtils.TruncateAt.START);

            }

        });
        animator.start();
    }


    /**
     * 关闭textView下拉动画
     */
    private void animateClose() {
        ValueAnimator animator = createDropAnimator(content, height, maxHeight);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                ViewGroup.LayoutParams layoutParams = content.getLayoutParams();
                layoutParams.height = maxHeight;
                content.setLayoutParams(layoutParams);
//                content.setMaxLines(6);
//                content.setEllipsize(TextUtils.TruncateAt.END);
            }

        });
        animator.start();
    }


    /**
     * 开启箭头图片旋转动画下拉动画
     */
    private void animationIvOpen(View v) {
        RotateAnimation animation = new RotateAnimation(0, 180,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        animation.setFillAfter(true);
        animation.setDuration(100);
        v.startAnimation(animation);
    }

    /**
     * 关闭箭头图片旋转动画下拉动画
     */
    private void animationIvClose(View v) {
        RotateAnimation animation = new RotateAnimation(180, 0,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        animation.setFillAfter(true);
        animation.setDuration(100);
        v.startAnimation(animation);
    }


    private void loadMoreContent() {
        moreContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isMoreContentTextExpan) {
                    contentShadow.setVisibility(View.INVISIBLE);
                    animateOpen();
                    animationIvOpen(moreContent);
                    isMoreContentTextExpan = true;
                } else {
                    contentShadow.setVisibility(View.VISIBLE);
                    animateClose();
                    animationIvClose(moreContent);
                    isMoreContentTextExpan = false;
                }
            }
        });
    }

    private void setWokrsCommentData() {
        mWorksCommentList.add(new WorksComment(R.drawable.yywtx23, "", "花开花落", "真不错真不错", "1天前", 2));
        mWorksCommentList.add(new WorksComment(R.drawable.yywtx24, "", "江意间", "哇！！！", "3天前", 5));
        mWorksCommentList.add(new WorksComment(R.drawable.yywtx25, "", "少年", "真好看", "3天前", 3));
        mWorksCommentList.add(new WorksComment(R.drawable.yywtx26, "", "记", "真不错真不错", "3天前", 2));
        mWorksCommentList.add(new WorksComment(R.drawable.yywtx27, "", "async", "美", "3天前", 1));
        mWorksCommentList.add(new WorksComment(R.drawable.yywtx28, "", "白茶清欢", "好想要同款", "4天前", 8));
    }

    private void setWokrsComment() {
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(mWorksCommentAdapter = new MyRecyclerViewAdapter<WorksComment>(mWorksCommentList, R.layout.rv_workscomment_item) {
            @Override
            public void handleData(InnerHolder holder, WorksComment item) {
                holder.setSrcResource(R.id.headPhoto, item.getFakePic());
                holder.setText(R.id.userName, item.getmUserName());
                holder.setText(R.id.content, item.getmContent());
                holder.setText(R.id.allReplyNums, item.getmReplyNums());
                holder.setText(R.id.time, item.getmTime());
                holder.setOnClickListener(R.id.allReplyNumsContainer, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });

            }
        });
    }

    private void setVideo() {
        vv.setVideoURI(VIDEO_URL);
        vv.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.d(TAG, "onPrepared: 准备完成");
                canPlay = true;
                Log.d(TAG, "onPrepared: " + vv.getDuration());
                sb.setMax(vv.getDuration());
                int width = vv.getWidth();
                int height = vv.getHeight();
                Log.d(TAG, "onPrepared: " + width);
                Log.d(TAG, "onPrepared: " + height);
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
                layoutParams.gravity = Gravity.CENTER;
                videoCover.setLayoutParams(layoutParams);
                loadCover(videoCover, VIDEO_URL, WorksDetailActivity.this);
            }
        });
        vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                playOrPause.setVisibility(View.VISIBLE);
                videoCover.setVisibility(View.VISIBLE);
                vv.seekTo(0);
                sb.setProgress(0);
                vv.pause();
            }
        });
        videoContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (canPlay && playOrPause.getVisibility() == View.VISIBLE) {
                    playOrPause.setVisibility(View.INVISIBLE);
                    videoCover.setVisibility(View.INVISIBLE);
                    vv.start();
                    mHandler.post(progressTask);
                } else if (canPlay && playOrPause.getVisibility() == View.INVISIBLE) {
                    playOrPause.setVisibility(View.VISIBLE);
                    vv.pause();
                    mHandler.removeCallbacks(progressTask);
                }
            }
        });

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                vv.seekTo(seekBar.getProgress());
            }
        });
        findViewById(R.id.sbContainer).setOnTouchListener(new View.OnTouchListener() {//mContentView是mProgressSeekBar的父view

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Rect seekRect = new Rect();
                sb.getHitRect(seekRect);

                if ((event.getY() >= (seekRect.top - 100)) && (event.getY() <= (seekRect.bottom + 100))
                        && event.getX() >= seekRect.left && event.getX() <= seekRect.right) {

                    float y = seekRect.top + seekRect.height() / 2;
                    float x = event.getX() - seekRect.left;//seekBar只接受相对x位置
                    if (x < 0) {
                        x = 0;
                    } else if (x > seekRect.width()) {
                        x = seekRect.width();
                    }
                    MotionEvent me = MotionEvent.obtain(event.getDownTime(), event.getEventTime(),
                            event.getAction(), x, y, event.getMetaState());
                    return sb.onTouchEvent(me);

                }
                return false;
            }
        });


    }


    private Runnable progressTask = new Runnable() {
        @Override
        public void run() {
            if (!vv.isPlaying()) {
                mHandler.removeCallbacks(progressTask);
                return;
            }
            sb.setProgress(vv.getCurrentPosition());
            mHandler.postDelayed(progressTask, 1000);
        }
    };

    /**
     * 加载第2秒的帧数作为封面
     * url就是视频的地址
     */
    public static void loadCover(ImageView imageView, Uri url, Context context) {
        Glide.with(context)
                .setDefaultRequestOptions(
                        new RequestOptions()
                                .frame(3000000)
                                .centerCrop()
                )
                .load(url)
                .into(imageView);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (picDialog != null) {
            picDialog = null;
        }
    }
}
